package com.example.ucs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ucs.bo.UserBO;
import com.example.ucs.domain.User;
import com.example.ucs.service.UserService;
import com.example.ucs.mapper.UserMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service
@CacheConfig(cacheNames = "cache_user")
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    @Override
    //Cacheable可以用来进行缓存的写入，将结果存储在缓存中，以便于在后续调用的时候可以直接返回缓存中的值，而不必再执行实际的方法
    @Cacheable(cacheNames = "cache_user", key = "#account", unless = "#result == null")
    public User getOneByAccount(String account) {
        return baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
    }


    @Override
    //CachePut:当需要更新缓存而不干扰方法的运行时 ，可以使用该注解。也就是说，始终执行该方法，并将结果放入缓存，注解参数与@Cacheable相同
    @CachePut(cacheNames = "cache_user", key = "#account")
    public User updateOneUser(String account, UserBO userBO) {
        User user = getOneByAccount(account);
        //只拷贝非空属性
        BeanUtil.copyProperties(userBO,
                user,
                CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        baseMapper.updateById(user);
        return user;
    }

    @Override
    //CacheEvict:删除缓存的注解,这对删除旧的数据和无用的数据是非常有用的。这里还多了一个参数(allEntries),设置allEntries=true时，可以对整个条目进行批量删除
    @CacheEvict(cacheNames = "cache_user", key = "#account")
    public void deleteOneUser(String account) {
        baseMapper.delete(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
    }


}




